package com.chenchao.javaarray;

import java.util.Arrays;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/7 20:05
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javaarray.SparseArray.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 */
public class SparseArray {
    public static void main(String[] args) {
        int[][] a = new int[11][11];
        a[1][2] = 1;
        a[2][3] = 2;
        //printArray(a);
        printArray(compressArray(a));
        printArray(restoreArray(compressArray(a)));
    }

    /**
     * compressArray 压缩二维矩阵
     *
     * @param array 要压缩的二维矩阵
     * @return
     */
    public static int[][] compressArray(int[][] array) {
        int sum = 0;//非零项的个数
        int[][] tempArray = new int[array.length * array[0].length][3];
        tempArray[0][0] = array.length;
        tempArray[0][1] = array[0].length;
        //获取二维数组行列长度
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                if (array[i][j] != 0) {
                    sum++;
                    tempArray[sum][0] = i;
                    tempArray[sum][1] = j;
                    tempArray[sum][2] = array[i][j];
                }
            }
        }
        int[][] compressedArray = new int[sum + 1][3];
        for (int i = 0; i < sum + 1; i++) {
            for (int j = 0; j < 3; j++) {
                compressedArray[i][j] = tempArray[i][j];
            }
        }
        compressedArray[0][2] = sum;//添加矩阵非零个数
        return compressedArray;
    }

    /**
     * restoreArray 还原二维矩阵
     *
     * @param array 要还原的二维矩阵
     * @return
     */
    public static int[][] restoreArray(int[][] array) {
        int[][] restoredArray = new int[array[0][0]][array[0][1]];
        for (int i = 1; i < array.length; i++) {
            for (int j = 0; j < 3; j++) {
                restoredArray[array[i][0]][array[i][1]] = array[i][2];
            }
        }
        return restoredArray;
    }

    /**
     * printArray 打印二维矩阵
     *
     * @param array 要打印的二维矩阵
     */
    public static void printArray(int[][] array) {
        for (int[] ints : array) {
            System.out.println(Arrays.toString(ints));
        }
    }
}
